package linear;

import java.util.Iterator;

public class Stack<T> implements Iterable<T>{
    //头结点
    private Node head;
    //计算元素个数
    private int N;

    //构造函数
    public Stack() {
        head = new Node(null, null);
        N = 0;

    }

    //判断栈中元素是否为空
    public boolean isEmpety() {
        return N == 0;
    }

    //把t元素压栈
    public void push(T t) {
        //找到首结点指向的下一个结点
        Node oldFirstNode = head.next;
        //创建新的结点
        Node newNode = new Node(t, null);
        //让头结点指向新结点
        head.next = newNode;
        //新的结点指向原来的第一个结点
        newNode.next = oldFirstNode;
        //长度加一
        N++;
    }

    //弹栈操作
    public T pop() {
        //找到首结点指向的下一个结点
        Node oldFirstNode = head.next;
        if (oldFirstNode == null) {
            return null;
        }
        head.next = head.next.next;
        //长度减一
        N--;
        return (T) oldFirstNode.item;
    }
    //获取元素个数
    public int size(){
        return N;
    }

    @Override
    public Iterator<T> iterator() {
        return new  SIterator();
    }
    public class SIterator implements Iterator<T>{
        private Node n=head;


        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public T next() {
            Node node=n.next;
            n=n.next;
            return (T) node.item;
        }
    }
}
